<script setup>
import { ref, watchEffect } from 'vue';

const props = defineProps({
  defaultChecked: Boolean,
  value: Boolean,
});
const emit = defineEmits(['update:value']);

const on = ref(props.defaultChecked);

function onSwitch () {
  on.value = !on.value;
  emit('update:value', on.value);
}

watchEffect(() => {
  on.value = props.value;
});

</script>

<template>
  <div
    :class="`switch ${ on ? '' : 'off' }`"
    @click="onSwitch"
  >
    <div :class="`btn ${ on ? '' : 'off' }`"></div>
  </div>
</template>

<style>
.switch {
  height: 100px;
  width: 200px;
  background: #1890ff;
  border-radius: 50px;
  padding: 8px;
  box-sizing: border-box;
}
.switch.off {
  background: #ccc;
}
/* 按钮在右侧的样式 */
.switch .btn {
  height: 84px;
  width: 84px;
  background: #fff;
  border-radius: 42px;
  float: right;
  transition: transform .3s ease, width .3s ease;
}
/* 按钮在左侧的样式 */
.switch .btn.off {
  transform: translateX(-100px);
}

/* 鼠标按下时的.switch .btn */
.switch:active .btn {
  width: 100px;
}

.switch:active .btn.off {
  transform: translateX(-84px);
}
</style>